<?php
namespace hangpu8\hpcms\service;

use Exception;

class CrudClas
{
    // 表名称
    private $table = '';
    // 表注释
    private $remark = '';
    // 应用名称
    private $appModule = '';
    // 类包根目录
    private $rootPath = '';
    /**
     * 构造函数
     *
     * @param string $table
     * @param string $appModule
     * @param string $remark
     */
    public function __construct(string $table,string $appModule,string $remark)
    {
        // 获得基础信息
        $this->table = $table;
        $this->remark = $remark;
        $this->appModule = $appModule;
    }
    /**
     * 生成添加数据操作方法
     *
     * @param array $action
     * @return string
     */
    public function addAction(array $action) : string
    {
        $str = '';
        $addRowForm = '';
        $addParamsRule = '';
        foreach ($action['children'] as $item)
        {
            // 数据验证
            if (!$item['param']) throw new Exception("请选择增加方法中的参数类型");
            if (!$item['formRule']) throw new Exception("请选择增加方法中的表单类型");

            // 组装数据
            $addRowForm .= "->addRow(\"{$item['field']}\",'{$item['formRule']}','{$item['remarks']}','{$item['formDefault']}')\n";
            $addParamsRule .= "* @Apidoc\Param(\"{$item['field']}\", type=\"{$item['param']}\",require=true,default=\"{$item['param_value']}\", desc=\"{$item['remarks']}\")\n";
        }
        if ($addRowForm && $addParamsRule)
        {
            $addRowForm = trim($addRowForm);
            $addParamsRule = trim($addParamsRule);
            $addParamsRule = "\n{$addParamsRule}";
        }
        $str = <<<str
        /**
         * @Apidoc\Title("{$action['title']}")
         * @Apidoc\Method("GET,POST")$addParamsRule
         */
        public function add()
        {
            \$model = new {$this->table}Model;
            if (request()->isPost())
            {
                \$data = \$this->request->post();
                try {
                    validate(\\app\\$this->appModule\\validate\\$this->table::class)
                        ->check(\$data);
                } catch (Exception \$e) {
                    list(\$code,\$msg) = explode("\\r\\n",\$e->getMessage());
                    return Json::fail(\$msg,(int)\$code);
                }
                if (\$model->save(\$data))
                {
                    return Json::successful([],'操作成功');
                }else{
                    return Json::fail('操作失败');
                }
            }else{
                \$formBuilder = new \hangpu8\hpcms\Utils\Builder\FormService();
                \$formBuilder->setMethod('GET');
                \$data = \$formBuilder
                $addRowForm
                ->create();
                return Json::successful(\$data);
            }
        }
        str;
        return $str;
    }
    /**
     * 生成删除操作方法
     *
     * @param [type] $action
     * @return string
     */
    public function delAction($action) : string
    {
        $str = '';
        $paramsRule = "";
        foreach ($action['children'] as $item)
        {
            // 数据验证
            if (!$item['param']) throw new Exception("请选择删除方法中的参数类型");
            if (!$item['formRule']) throw new Exception("请选择删除方法中的表单类型");

            // 组装数据
            $paramsRule .= "* @Apidoc\Param(\"{$item['field']}\", type=\"{$item['formRule']}\",require=true,default=\"{$item['formDefault']}\", desc=\"{$item['remarks']}\")\n";
        }
        if ($paramsRule)
        {
            $paramsRule = trim($paramsRule);
            $paramsRule = "\n{$paramsRule}";
        }
        $str = <<<str
        /**
         * @Apidoc\Title("删除")$paramsRule         
         * @Apidoc\Method("DELETE")
         */
        public function del(\$id)
        {
            if ({$this->table}Model::destroy(\$id))
            {
                return Json::successful([],'操作成功');
            }else{
                return Json::fail('操作失败');
            }
        }
        str;
        return $str;
    }
    /**
     * 生成修改操作方法
     *
     * @param array $action
     * @return string
     */
    public function editAction(array $action) : string
    {
        $str = '';
        $addRowForm = '';
        $addParamsRule = '';
        foreach ($action['children'] as $item)
        {
            // 数据验证
            if (!$item['param']) throw new Exception("请选择修改方法中的参数类型");
            if (!$item['formRule']) throw new Exception("请选择修改方法中的表单类型");

            // 组装数据
            $addRowForm .= "->addRow('{$item['field']}','input','{$item['remarks']}')\n";
            $addParamsRule .= "\t* @Apidoc\Param(\"{$item['field']}\", type=\"{$item['param']}\",require=true,default=\"\", desc=\"\")\n";
        }
        if ($addRowForm && $addParamsRule)
        {
            $addRowForm = trim($addRowForm);
            $addParamsRule = trim($addParamsRule);
            $addParamsRule = "\n{$addParamsRule}";
        }
        $str = <<<str
        /**
         * @Apidoc\Title("{$action['title']}")
         * @Apidoc\Method("GET,POST")$addParamsRule
         */
        public function edit(\$id)
        {
            \$model = new {$this->table}Model;
            if (request()->isPost())
            {
                \$data = \$this->request->post();
                try {
                    validate(\\app\\$this->appModule\\validate\\$this->table::class)
                        ->check(\$data);
                } catch (Exception \$e) {
                    list(\$code,\$msg) = explode("\\r\\n",\$e->getMessage());
                    return Json::fail(\$msg,(int)\$code);
                }
                if (\$model->save(\$data))
                {
                    return Json::successful([],'操作成功');
                }else{
                    return Json::fail('操作失败');
                }
            }else{
                \$map['id'] = \$id;
                \$info = \$model->where(\$map)->find();
                \$formBuilder = new \hangpu8\hpcms\Utils\Builder\FormService();
                \$formBuilder->setMethod('GET');
                \$data = \$formBuilder
                $addRowForm
                ->setFormData(\$info)
                ->create();
                return Json::successful(\$data);
            }
        }
        str;
        return $str;
    }

    /**
     * 生成列表操作方法
     *
     * @param array $action
     * @return string
     */
    public function listAction(array $action) : string
    {
        $str = '';
        $column = '';
        $columnKey = 'id';
        foreach ($action['children'] as $item)
        {
            // 数据验证
            if (!$item['param']) throw new Exception("请选择列表方法中的参数类型");
            if (!$item['formRule']) throw new Exception("请选择列表方法中的表单类型");

            // 组装数据
            $column .= "->addColumn('{$item['field']}', '{$item['remarks']}')\n";
            if ($item['primary'])
            {
                $columnKey = $item['field'];
            }
        }
        if ($column)
        {
            
            $column = trim($column);
            $column = "\n{$column}";
        }
        $router_prefix = "{$this->appModule}/{$this->table}";
        $str .= <<<str
        /**
         * @Apidoc\Title("列表")
         */
        public function index()
        {
            \$model = new {$this->table}Model;
            \$list = \$model->order('{$columnKey} desc')->paginate()->toArray();
            \$builder = new \hangpu8\hpcms\Utils\Builder\ListBuilder;
            \$data = \$builder
                ->addColumn('rightButtonList', '操作', [
                    'type' => 'template',
                    'template' => 'rightButtonList'
                ])
                ->addTopButton('add', '添加', [
                    'title'         => '添加数据',
                    'apiurl'        => '{$router_prefix}/add',
                ])
                ->addRightButton('edit', '修改', ['api' => '{$router_prefix}/edit', 'title' => '修改数据'])
                ->addRightButton('delete', '删除', [
                    'api' => '{$router_prefix}/del',
                    'title' => '确认要删除该数据吗？',
                    'modalType' => 'confirm',
                    'width' => '600',
                    'okText' => '确认删除',
                    'cancelText' => '取消操作',
                    'content' => '<p>删除该数据不可恢复</p>',
                ]){$column}
                ->setData(\$list['data'])
                ->create();
                return Json::successful(\$data);
        }
        str;
        return $str;
    }

    /**
     * 生成详情操作方法
     *
     * @param array $action
     * @return string
     */
    public function infoAction(array $action) : string
    {
        $str = <<<str
        
        str;
        return $str;
    }
}